package com.songminju.jsong_httpserver.server.bio;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import com.songminju.jsong_httpserver.HttpHandler;

/**
@todo
@description
@author songminju
@date 2017年12月5日
*/
public class RequestAdapter implements Runnable{
	ExecutorService threadPool = Executors.newCachedThreadPool();
	private LinkedBlockingQueue<RequestConnection> sockets = new LinkedBlockingQueue<>();
	private HttpHandler handler = null;
	private Logger logger = Logger.getLogger(this.getClass());
	
	public RequestAdapter(HttpHandler handler) {
		this.handler = handler;
	}
	
	public void put(RequestConnection rc) {
		try {
			logger.debug("try to put a request socket to req queue.");
			sockets.put(rc);
			logger.debug("had put a request socket to req queue.");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			try {
				logger.debug("wait for take a client req,");
				RequestConnection rc = sockets.take();
				logger.debug("had taked a client req,");
				if(rc.getSocket().isClosed()) {
					continue;
				}
				HtttpHandlerTask task = new HtttpHandlerTask(rc,this);
				threadPool.submit(task);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public HttpHandler getHttpHandler() {
		return handler;
	}
}
